package cn.tedu.rabbitmq.test.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class DlxDeclare {
    private Channel channel;
    @Before
    public void initChannel() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.8.100");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
    }
    // 为案例中声明各种名称、字符串、设置常量
    // 业务交换机名字
    private final static String BIZ_EXCHANGE_NAME = "biz_exchange";
    // 业务队列名字
    private final static String BIZ_QUEUE_NAME = "biz_queue";
    // 死信交换机名字
    private final static String DLX_EXCHANGE_NAME = "dlx_exchange";
    // 死信队列名字
    private final static String DLX_QUEUE_NAME = "dlx_queue";
    // 死信路由key
    private final static String DLX_ROUTING_KEY = "dlx_routing_key";
    @Test
    public void dlxDeclare() throws IOException {
        // 声明两个交换机
        channel.exchangeDeclare(BIZ_EXCHANGE_NAME,"fanout");
        channel.exchangeDeclare(DLX_EXCHANGE_NAME,"direct");
        // 声明死信队列
        channel.queueDeclare(DLX_QUEUE_NAME,false,false,false,null);
        // 声明业务队列
        Map<String,Object> args=new HashMap<>();
        // 消息超时时间 产生死信条件之一
        args.put("x-message-ttl",10000);
        // 业务队列绑定死信交换机
        args.put("x-dead-letter-exchange",DLX_EXCHANGE_NAME);
        // 业务队列绑定死信路由key
        args.put("x-dead-letter-routing-key",DLX_ROUTING_KEY);
        channel.queueDeclare(BIZ_QUEUE_NAME,false,false,false,args);
        // 声明绑定关系 一定是队列绑定交换机
        channel.queueBind(BIZ_QUEUE_NAME,BIZ_EXCHANGE_NAME,"");
        // 声明绑定关系 死信队列 使用死信路由key 绑定死信交换机
        channel.queueBind(DLX_QUEUE_NAME,DLX_EXCHANGE_NAME,DLX_ROUTING_KEY);
    }
}
